package com.preoffer.shortlink.project.handler;

import cn.hutool.core.util.StrUtil;
import com.preoffer.shortlink.project.common.convention.exception.ClientException;
import com.preoffer.shortlink.project.config.GotoDomainWhiteListConfiguration;
import com.preoffer.shortlink.project.dao.entity.ShortLinkDO;
import com.preoffer.shortlink.project.dto.biz.ShortLinkRiskDTO;
import com.preoffer.shortlink.project.dto.req.ShortLinkCreateReqDTO;
import com.preoffer.shortlink.project.tookit.LinkUtil;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

@Aspect
@Component
@RequiredArgsConstructor
public class DoJoinPoint {

    private final GotoDomainWhiteListConfiguration gotoDomainWhiteListConfiguration;

    @Pointcut("@annotation(com.preoffer.shortlink.project.annotation.VerificationWhitelist)")
    public void aopPoint() {
    }

    @Around("aopPoint()")
    public Object doRouter(ProceedingJoinPoint jp) throws Throwable {
        Object argument = jp.getArgs()[0];
        ShortLinkRiskDTO shortLinkRiskDTO = new ShortLinkRiskDTO();
        BeanUtils.copyProperties(argument,shortLinkRiskDTO);
        String originUrl = shortLinkRiskDTO.getOriginUrl();

        Boolean enable = gotoDomainWhiteListConfiguration.getEnable();
        if (enable == null || !enable) {
            return jp.proceed();
        }
        String domain = LinkUtil.extractDomain(originUrl);
        if (StrUtil.isBlank(domain)) {
            throw new ClientException("跳转链接填写错误");
        }
        List<String> details = gotoDomainWhiteListConfiguration.getDetails();
        if (!details.contains(domain)) {
            throw new ClientException("演示环境为避免恶意攻击，请生成以下网站跳转链接：" + gotoDomainWhiteListConfiguration.getNames());
        }
        return jp.proceed();
    }
}
